package normalsys.demo.base.util.file;

import java.io.InputStream;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

/**
 * Project Name: mongotest
 * File Name: FileUtil
 * Package Name: com.test.mongo.common.util.string
 * Date: 2018/4/27  11:40
 * Copyright (c) 2018, tianyul All Rights Reserved.
 * 七牛文件上传工具类
 */
public class FileClient {
    private String accessKey;//公钥
    private String secretKey;//密钥
    private String bucket;//存储空间
    private String url;//返回的地址头
    private int zone;//地区

    /**
     * 初始化
     * @param accessKey
     * @param secretKey
     * @param bucket
     * @param url
     */
    public FileClient(String accessKey, String secretKey, String bucket, String url,int zone) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.bucket = bucket;
        this.url = url;
        this.zone = zone;
    }

    /**
     * 文件流上传
     * @param in
     * @return
     */
    public String uploadFile(InputStream in, String format, int zone) {

        InputStream is;
        if("jpg".equals(format) || "jpeg".equals(format)) {
            //图片压缩
            is = ImgUtil.getFileCompressStream(in, format);
        } else {
            is = in;
        }

        Zone area;
        if(0 == zone) {
            area = Zone.zone0();
        } else if(1 == zone) {
            area = Zone.zone1();
        } else {
            area = Zone.zone2();
        }

        String name = null;
        // 构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(area);
        // ...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        // ...生成上传凭证，然后准备上传
        String key = null;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(is, key, upToken, null, null);
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            name = url + putRet.hash;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                return "";
            }
        }
        return name;
    }
}
